package com.example.pureman.myapplication.aidl;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.example.pureman.myapplication.IMyAidlInterface;
import com.example.pureman.myapplication.R;
import com.example.pureman.myapplication.utils.CommonLog;

public class AIDLActivity extends AppCompatActivity {

    private IMyAidlInterface myAidlInterface = null;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myAidlInterface = IMyAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_aidl);

        //开启服务
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);

        final TextView textView = (TextView) findViewById(R.id.id_aidl_textview);

        findViewById(R.id.id_aidl_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    CommonLog.d("onClick-->" + myAidlInterface);
//                    textView.setText(myAidlInterface.getValue());
                    textView.setText(myAidlInterface.getValue() + myAidlInterface.getQuake().getDate().toString());
                } catch (RemoteException e) {

                }
            }
        });
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //开启服务
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);
        //断开与远程Service的连接
        unbindService(serviceConnection);
    }
}
